package com.util;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class EmptyValidator implements ConstraintValidator<Empty,String> {

    private int min = 0;

    private int max = Integer.MAX_VALUE;
 
    @Override
    public void initialize(Empty constraintAnnotation) {
        min = constraintAnnotation.min();
        max = constraintAnnotation.max();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }
 
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        log.info("【{}】值【{}】",context.getDefaultConstraintMessageTemplate(),value);
        if(value == null || "".equals(value)) {
            return false;
        }
        if("".equals(value.trim())) {
            return false;
        }
        if(value.length() < min){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("参数至少"+min+"个字符").addConstraintViolation();
            return false;
        }
        if(value.length() > max){
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("参数必须小于"+max+"个字符").addConstraintViolation();
            return false;
        }
        return true;
    }
}